from datetime import datetime, timezone
import os
from zoneinfo import ZoneInfo
import time
from typing import Dict
import json
import pytest
import allure
from playwright.sync_api import Page,TimeoutError
from pytest import Item
from tool_class.handle_loguru import log
# 本地插件注册
from tool_class.page_handle_base import PageHandleBase

pytest_plugins = [  # noqa
    'plugins.pytest_playwright',  # 使用本地pytest_playwright文件
    # 'plugins.pytest_base_url_plugin' # noqa
]

def login(page):
    try:
        locator_username = page.get_by_placeholder("账号")
        locator_password = page.get_by_placeholder("密码")
        locator_code = page.get_by_placeholder("请输入验证码")
        locator_login_btn = page.get_by_test_id("login-1004")
        locator_username.fill("ft_autoTest1")
        locator_password.fill('12345678')
        locator_code.fill('2587')
        locator_login_btn.click()
        # 表示页面在至少500毫秒内没有新的网络请求，或者网络请求的数量低于某个阈值。这通常意味着页面的主要资源已经加载完成，但可能还有一些异步请求在进行中
        page.wait_for_load_state('networkidle')
        return True
    except TimeoutError as e:
        log.error("登录超时")
        log.error(e)

@pytest.mark.run(order=0)
@pytest.fixture(scope='module')
def session_page(page: Page):
    try:
        print("for each--start: 打开新页面访问登录页")
        page.set_viewport_size({"width": 1780, "height": 1080})
        page.goto("/ins/#/login")  # 登录页面地址
        login(page)
        time.sleep(2)
        local_storage_value = page.evaluate("() => localStorage.getItem('token')")
        log.info(f"当前登录token：{local_storage_value}")
    except Exception as e:
        # 如果有异常，打印错误信息
        print(f"发生错误：{e}")
        raise  # 重新抛出当前捕获的异常
    return page


@pytest.hookimpl(tryfirst=True,hookwrapper=True)
def pytest_runtest_makereport(item,call):
    outcome = yield
    rep = outcome.get_result()
    if rep.when == 'call' and rep.failed:
        page = item.funcargs.get('session_page')
        handle = PageHandleBase(page)
        page.screenshot(path="output_log/screenshot.png")
        # 将截图添加到 Allure 报告中
        with open("output_log/screenshot.png", 'rb') as file:
            binary_data = file.read()
            allure.attach(binary_data, name='失败截图', attachment_type=allure.attachment_type.PNG)
        if "/ins/#/login" in page.url:
            log.info("当前失败时处于登录页面，需要重新登录。")
            log.info(f"当前位置-------》{page.url}")
            login(page)
            log.info(f"跳转位置-------》{PageHandleBase.current_position}")
            handle.goto_local(**PageHandleBase.current_position)
        if PageHandleBase.current_position:
            if PageHandleBase.current_position["url_path"] not in page.url:
                log.info("当前失败时处于页面不是该用例的指定页面，需要跳转到指定页面。")
                log.info(f"当前位置-------》{page.url}")
                log.info(f"跳转位置-------》{PageHandleBase.current_position}")
                handle.goto_local(**PageHandleBase.current_position)

def pytest_runtest_call(item: Item):
    """allure 报告自定义配置"""
    # 动态添加测试类的 allure.feature()
    if item.parent.obj.__doc__:  # noqa
        allure.dynamic.feature(item.parent.obj.__doc__)  # noqa
        # print(item.parent.obj.__doc__)                      # noqa
    # 动态添加测试用例的title 标题 allure.title()
    if item.function.__doc__:  # noqa
        allure.dynamic.title(item.function.__doc__)  # noqa
        print(item.function.__doc__)  # noqa